package com.gang.blog.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gang.blog.domain.Comment;
import com.gang.blog.domain.Comment2;
import com.gang.blog.domain.User;
import com.gang.blog.service.CommentService;
import com.gang.blog.service.UserService;



@Controller
@Transactional
@RequestMapping("/comment")
public class CommetController {
	@Resource
	private CommentService commentService;
	@Resource
	private UserService userService;
	
	public void setCommentService(CommentService commentService) {
		this.commentService = commentService;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 增加评论
	 * @param commentContent
	 * @param articleId
	 * @param request
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Map<String, Object> addCommet(@Param("userId")Integer userId,@Param("commentContent") String commentContent,@Param("articleId") Integer articleId,HttpServletRequest request){
		Comment comment = new Comment();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//User user = (User) request.getSession().getAttribute("user");
		User user = this.userService.getUserById(userId);
		comment.setArticleId(articleId);
		comment.setCommentContent(commentContent);
		comment.setCommentDate(new Date());
		comment.setUser(user);
		boolean mark = this.commentService.insertComment(comment);
		if(mark){
			//向ajax返回userName，和判断字段result
			resultMap.put("user", user);
			resultMap.put("result", true);
			//resultMap.put("userName", user.getUserName());
		}else{
			resultMap.put("result", false);
		}
		return resultMap;
	}
	/**
	 * 获取该文章的所有评论
	 * @param articleId
	 * @param model
	 * @return 返回存放commentList的map到ajax回调函数
	 */
	//responseBody 注解将返回的list和对象解析成json字符串
	@ResponseBody
	@RequestMapping(value="/getCommentList",method=RequestMethod.GET)
	public  Map<String, Object> getCommentList(@Param("articleId")Integer articleId){
		Map<String, Object> result = null;
		//调用commentService接口，按articleId查找comment2的列表
		List<Comment2> commentList = this.commentService.getCommentAndUser(articleId);
		result = new HashMap<String, Object>();
		//将list放入map
		result.put("commentList", commentList);
 		return result;
	}
	 
}